// 笔试强训2025/3/11
// 数组中两个字符串的最小距离

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n; string str1, str2;
    cin >> n >> str1 >> str2;
    vector<string> strs(n);
    int count1 = 0, count2 = 0;
    for (int i = 0; i < n; i++)
    {
        cin >> strs[i];
        if (strs[i] == str1) count1++;
        if (strs[i] == str2) count2++;
    }
    if (count1 == 0 || count2 == 0)
    {
        cout << -1 << endl;
        return 0;
    }

    int left = 0, right = n - 1;
    int ans = n;
    while (left < right && (count1 >= 0 || count2 >= 0))
    {
        while (count1 > 0 && strs[left] != str1)
        {
            left++;
        }
        count1--;
        
        while (count2 > 0 && strs[right] != str2)
        {
            right--;
        }
        count2--;
        
        if (left > right)
            ans = min(ans, left - right);
        else
            ans = right - left;
        if (count1 > 0) left++;
        if (count2 > 0) right--;
    }

    cout << ans << endl;
}
// 64 位输出请用 printf("%lld")